import os
import time
import imageio
import live555
import threading
import acl
import numpy as np
from queue import Queue
from .AscendDvpp import DvppInfo

class AscendStreamPuller(object):
    def __init__(self, channelID, streamName, video_path,q):
        self.channelID = channelID
        self.streamName = streamName
        self.video_path = video_path
        self.frame_data = None
        self.queue = q 
        self.frame = 0
        self.index = 0
    def runStream(self):
        useTCP = True
        live555.startRTSP(self.streamName, self.oneFrame, useTCP)
        live555.runEventLoop()

    def delStream(self):
        live555.stopEventLoop()

    def getImage(self,imageName):
        return imageio.imread(imageName)

    def getVideo(self,videoName):
        return imageio.get_reader(videoName, 'ffmpeg')

    def set_queue(self, queue: Queue):
        self.queue = queue

    def oneFrame(self, codecName, data, sec, usec, durUSec):
        #print('frame for %s: %d bytes' % (codecName, len(bytes)))
        if self.queue == None:
            return
        if self.queue.full():
            #print('---------data_collection------------queue is full')
            return
        else:
            if codecName == 'H264':
                    #print('queue: {} bytes'.format(self.video_data.frame_id))
                    video_data = DvppInfo()
                    np_data = np.frombuffer(data, dtype=np.uint8)
                    print(np_data)
                    header = np.array([0,0,0,1],np.uint8)
                    np_frame = np.concatenate((header,np_data))
                
                    #print(np_frame)
                    ptr = acl.util.numpy_to_ptr(np_frame)
                    print('data len:', len(data))
                    video_data.buffer_ptr = ptr
                    video_data.buffer_size = np_frame.size * np_frame.itemsize
                    video_data.width = 1280
                    video_data.height = 720
                    self.frame += 1
                    video_data.frame_id = self.frame
                    video_data.channel_id = self.channelID                 
                    self.queue.put(video_data)


    def run(self, q: Queue):
        self.set_queue(q)
        if self.streamName:
            self.getStream(oneFrame)
            self.runStream()
        elif self.video_path:
            image = self.getVideo()
            for i, im in enumerate(image):
                print('Mean of frame %i is %1.1f' %(i,im.mean()))
        else:
            print(".............")
        
if __name__ == '__main__':
    streamName = "rtsp://wowzaec2demo.streamlock.net/vod/mp4:BigBuckBunny_115k.mov"
    asPuller = AscendStreamPuller(1,streamName,"/root",None)

    # read video sample
    #image = asPuller.getVideo("dump.flv")
    #for i, im in enumerate(image):
    #    print('Mean of frame %i is %1.1f' %(i,im.mean()))

    # read stream sample
    t = threading.Thread(target=asPuller.runStream, args=())
    t.setDaemon(True)
    t.start()

    endTime = time.time() + 300
    while time.time() < endTime:
        time.sleep(1)

    asPuller.delStream()
    t.join()
